package com.study.servlet;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet(urlPatterns = "/hello")
public class HelloServlet implements Servlet {

    @Resource(lookup = "java:/comp/env", name = "jdbc/DemoDataSource")
    private DataSource derbyDataSource;

    @Override
    public void init(ServletConfig config) throws ServletException {

    }

    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

    @Override
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        try (Connection connection = derbyDataSource.getConnection()) {
            res.getWriter().println("获取 JDBC 连接成功");
            PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM HELLO");
            ResultSet result = preparedStatement.executeQuery();
            res.getWriter().println("<table>");
            while (result.next()) {
                res.getWriter().println("<tr>");
                res.getWriter().println("<td>" + result.getInt("ID") + "</td><td>" + result.getString("CONTENT") + "</td>");
                res.getWriter().println("</tr>");
            }
            res.getWriter().println("</table>");
        } catch (SQLException e) {
            res.getWriter().println(e.getMessage());
        }
    }

    @Override
    public String getServletInfo() {
        return null;
    }

    @Override
    public void destroy() {

    }

}
